<?php
/**
 * Created by PhpStorm.
 * User: elliot
 * Date: 2017/4/1
 * Time: 16:16
 */
namespace app\admin\controller;
use app\models\Bases;
use think\Exception;

class Kernel extends Base{

    /**
     * 核心内参展示页面
     * @return \think\response\View
     * @throws \Exception
     */
    public function kernelShow(){
        $article_model = new Bases('article');
        $get = input('param.');
        if(!empty($get)){
            $search = search($get, 'create_time', 'title');
            $result = $article_model -> page($search['condition'], 'create_time desc', 15);
            return view('articleList',['result'=>$result, 'display'=>$get]);
        }
        $result = $article_model -> page('', 'create_time desc', 15);
        if(empty($result)){
            throw new \Exception('很遗憾，没有数据', 10031);
        }
        return view('articleList', ['result'=>$result]);
    }

    /**
     * 新增文章
     * @return [type] [description]
     */
    public function kernelAdd()
    {
        $article_id = intval(input('id'));
        $articleAdd = new Bases('article');
        $user = new Bases('admin');
        try{
            $type_id = empty(input('type_id'))?1 : input('type_id');
            if(Request() -> isPost()){
                $post = input('param.');
                $post['type_id'] = $type_id;
                $post['summary'] = html_entity_decode($post['summary']);
                $post['create_time'] = $post['lastest_modify'] = time();
                $post['author'] = $user -> value(array('id'=>cookie('login')), 'username');
                //标题和摘要必填
                if(empty($post['title']) || empty($post['summary'])){
                    throw new \LogicException('完成页面信息填写', 10013);
                }
                //获取上传文件
                if(empty($_FILES)){
                    throw new \LogicException('没有上传文件',10021);
                }
                $file = request() -> file('file');
                if(!$file){
                    throw  new \LogicException('上传文件失败',10023); //如果文件上传失败，抛出异常信息
                }
                $info = $file ->validate(['size'=>2000000000, 'ext'=>'pdf'])->rule('uniqid')-> move(ROOT_PATH . 'public' . DS . 'uploads'.DS.'kernel');
                if(!$info){
                    throw  new \LogicException($file->getError(),10023); //如果文件上传失败，抛出异常信息
                }
                //上传成功获取文件信息
                if($info){
                    $post['attachment'] = $info->getFilename();
                    $post['attachment_path'] = DS.'uploads'.DS.'kernel'.DS.$post['attachment'];
                    $result = $articleAdd ->insertData($post);
                    if(!$result){
                        throw new \LogicException('操作失败',406);
                    }
                    return self::formatSuccessResult();
                }
            }
        }catch(\Exception $e){
            return self::formatResult($e->getCode(), $e->getMessage());
        }
        $where['id'] = $article_id;
        $result = $articleAdd -> find($where);
        return view('articleAdd');
    }

    /**
     * 查看文章信息
     * @return [type] [description]
     */
    public function kernelView(){
        $articleView = new Bases('article');
        $article_id = intval(input('id'));
        try{
            $where = array('id'=>$article_id);
            $article = $articleView->find($where);
            if(empty($article)){
                throw new \LogicException('没有数据', 406);
            }
            return view('articleView',['result'=>$article]);
        }catch(\Exception $e){
            return self::formatResult($e->getCode(), $e->getMessage());
        }
    }

    /**
     * 编辑保存文章
     * @return [type] [description]
     */
    public function kernelSave(){
        $articleEdit = new Bases('article');
        $article_id = intval(input('id'));
        try{
            if(Request()->ispost()){
                $post = input('param.');
                $post['summary'] = html_entity_decode($post['summary']);
                $post['lastest_modify'] = time();
                //标题和摘要必填
                if(empty($post['title']) || empty($post['summary'])){
                    throw new \LogicException('标题和摘要不可为空', 10013);
                }
                unset($post['uploadfile-1']);
                //用户未上传新文件进行更新操作
                if(array_key_exists('image', $post)){
                    unset($post['image']);
                    $result = $articleEdit -> updateData($post);
                    if(!$result){
                        throw new \LogicException('操作失败', 1024);
                    }
                    return self::formatSuccessResult();
                }else{
                    //用户上传了新文件进行更新操作
                    $file = request()->file('image');
                    if($file){
                        //移动到文件上传目录
                        $info = $file-> validate(['size'=>200000, 'ext'=>'pdf'])->rule('uniqid')->move(ROOT_PATH.'public'.DS.'uploads'.DS.'kernel');
                        if($info){
                            //获取文件名和路径
                            $post['attachment'] = $info->getFilename();
                            $post['attachment_path'] = DS.'uploads'.DS.'kernel'.DS.$post['attachment'];
                        }else{
                            //文件类型错误
                            throw new \LogicException($file->getError(),1024);
                        }
                    }else{
                        //上传失败
                        throw new \LogicException('上传失败', 1024);
                    }

                }
                $result = $articleEdit -> updateData($post);
                if(!$result){
                    throw new \LogicException('操作失败');
                }
                return self::formatSuccessResult();
            }
        }catch(\Exception $e){
            return self::formatResult($e->getCode(), $e->getMessage());
        }

        $where = array('id'=>$article_id);
        $article = $articleEdit->find($where);
        return view('articleSave',['result'=>$article]);
    }


    /**
     * 删除文章
     * @return [type] [description]
     */
    public function kernelDel(){
        $articleDel = new Bases('article');
        $article_id = intval(input('id'));
        try{
            $where['id'] = $article_id;
            $filePath = $articleDel -> value($where, 'attachment_path');
            //删除文件
            $fileUrl = ROOT_PATH.'public'.$filePath;
            //文件不存在，直接删除数据库记录
            if(!file_exists($fileUrl)){
                $result = $articleDel->deleteDaPtaByPrimaryKey($article_id);
                if(!$result){
                    throw new \LogicException('删除失败', 1023);
                }
                return self::formatSuccessResult();
            }
            //文件存在，删除文件和记录
            $delFile = unlink($fileUrl);
            if(!$delFile){
                throw new \LogicException(1023,'未能删除系统中的文件，指向文件可能不存在');
            }
            //删除mysql记录
            $result = $articleDel->deleteDaPtaByPrimaryKey($article_id);
            if(!$result){
                throw new \LogicException('删除失败', 1023);
            }
            return self::formatSuccessResult();
        }catch(\Exception $e){
            return self::formatResult($e->getCode(), $e->getMessage());
        }
    }

}